<template>
  <div>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" style="margin: 20px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" style="width:50%"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-select v-model="formData.tags" multiple placeholder="请选择标签" style="width: 50%">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <VMarkdownEditor v-model="formData.content" locale="zh" :upload-action="handleUpload" class="markdown-editor" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { VMarkdownEditor } from 'vue3-markdown';
import 'vue3-markdown/dist/vue3-markdown.css';
import { createArticle, getTag } from '@/api/modules'
import { useHandleData } from "@/hooks/useHandleData"
import { useUserStore } from "@/stores/use"
interface User {
  name: string;
  id: number;
}
interface Tag {
  label: string;
  value: number;
}
const userStore = useUserStore()
const formRef = ref();
const formData = reactive({
  title: '',
  content: '',
  tags: []
});
const options = ref<Tag[]>([])
const formRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  tags: [{ required: true, message: '请选择标签', trigger: 'change' }],
}

const getTableData = async () => {
  const res = await getTag()
  const date = res.data.data.labels
  options.value = date.map((item: User) => ({
    label: item.name,
    value: item.id
  }))
}
onMounted(getTableData)
const handleUpload = (file: string) => {
  console.log(file);
  return 'https://i.postimg.cc/52qCzTVw/pngwing-com.png';
}
const handleSubmit = async () => {
  await formRef.value.validate();
  if (!formData.title && !formData.content && formData.tags.length === 0) return;
  const params = {
    title: formData.title,
    content: formData.content,
    labelIds: formData?.tags || [],
    authorId: userStore.id
  }
  await useHandleData(createArticle, params, '发布', 'success');
}
</script>
<style scoped>
.markdown-editor {
  min-height: 60vh;
  max-height: 60vh;
}
</style>
